package com.ldn.basic.utils.ali;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import com.aliyun.teaopenapi.models.*;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author 李大牛家的牛 (scafel@163.com) 
 * @createDate 2024/7/11 - 15:43
 * @description 阿里云短信工具类
 **/
@Slf4j
@Component
public class ALiSmsUtils {

    @Value("${ali.sms.keyId}")
    private String _keyId;
    private static String keyId;

    @Value("${ali.sms.keySecret}")
    private String _keySecret;
    private static String keySecret;

    @Value("${ali.sms.signName}")
    private String _signName;
    private static String signName;

    @Value("${ali.sms.verificationCode}")
    private String _verificationCode;
    private static String verificationCode;


    @PostConstruct
    public void init() {
        setKeyId(_keyId);
        setKeySecret(_keySecret);
        setSignName(_signName);
        setVerificationCode(_verificationCode);
    }

    public static void setKeyId(String keyId) {
        ALiSmsUtils.keyId = keyId;
    }

    public static void setKeySecret(String keySecret) {
        ALiSmsUtils.keySecret = keySecret;
    }

    public static void setSignName(String signName) {
        ALiSmsUtils.signName = signName;
    }

    public static void setVerificationCode(String verificationCode) {
        ALiSmsUtils.verificationCode = verificationCode;
    }


    /**
     * 使用AK&SK初始化账号Client
     * @return Client
     */
    private static com.aliyun.teaopenapi.Client createClient() throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // 必填，您的 AccessKey ID
                .setAccessKeyId(keyId)
                // 必填，您的 AccessKey Secret
                .setAccessKeySecret(keySecret);
        // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.teaopenapi.Client(config);
    }

    /**
     * API 相关
     * @return OpenApi.Params
     */
    private static com.aliyun.teaopenapi.models.Params createApiInfo() throws Exception {
        return new Params()
                // 接口名称
                .setAction("SendSms")
                // 接口版本
                .setVersion("2017-05-25")
                // 接口协议
                .setProtocol("HTTPS")
                // 接口 HTTP 方法
                .setMethod("POST")
                .setAuthType("AK")
                .setStyle("RPC")
                // 接口 PATH
                .setPathname("/")
                // 接口请求体内容格式
                .setReqBodyType("json")
                // 接口响应体内容格式
                .setBodyType("json");
    }


    public static boolean sendSMS(String phoneNumber, String code) {
        boolean result = false;
        try {
            com.aliyun.teaopenapi.Client client = createClient();
            com.aliyun.teaopenapi.models.Params params = createApiInfo();
            java.util.Map<String, Object> queries = new java.util.HashMap<>();
            queries.put("PhoneNumbers", phoneNumber);
            queries.put("SignName", signName);
            queries.put("TemplateCode", verificationCode);
            queries.put("TemplateParam", "{\"code\":\""+ code +"\"}");
            System.out.println(queries);
            com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
            com.aliyun.teaopenapi.models.OpenApiRequest request = new com.aliyun.teaopenapi.models.OpenApiRequest()
                    .setQuery(com.aliyun.openapiutil.Client.query(queries));
            // 返回值为 Map 类型，可从 Map 中获得三类数据：响应体 body、响应头 headers、HTTP 返回的状态码 statusCode。
            Map<String, ?> res = client.callApi(params, request, runtime);
            if (res.get("body") != null) {
                JSONObject body = JSONUtil.parseObj(res.get("body"));
                String bodyCode = (String) body.get("Code");
                if (bodyCode.equals("OK")) {
                    log.info("短信验证码发送成功！code=>{}",  body.get("Message"));
                    result = true;
                } else {
                    log.error("短信验证码发送失败！code=>{}", body.get("Message"));
                }
            }
        } catch (Exception ex) {
            log.error("短信验证码发送失败！ex=>{}", ex.getMessage());
        }
        return result;
    }

}
